# Copyright (c) 2021-2023 Alibaba Cloud Computing Ltd.
# SPDX-License-Identifier: MulanPSL-2.0
import re  
import os 
import subprocess

from datetime import datetime

USAGE = "python3 packup.py"

SPEC_NAME = "keentune-ui.spec"
PACKAGE_NAME = "keentune-ui"
PACKAGE_FILEs = os.listdir("./")
PACKAGE_FILEs.remove("build")
PACKAGE_FILEs.remove(".gitignore")

source_dir = os.path.split(os.path.realpath(__file__))[0]

def sysCommand(command: str, cwd: str = "./"):
    result = subprocess.run(
        command,
        shell=True,
        close_fds=True,
        cwd=cwd,
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE
    )

    suc = (result.returncode == 0)
    out = result.stdout.decode('UTF-8', 'strict').strip()
    error = result.stderr.decode('UTF-8', 'strict').strip()

    if not suc:
        return suc, error

    else:
        return suc, out

def checkspec():
    print("[+] check spec file:{}".format(SPEC_NAME))

    with open(os.path.join(source_dir, SPEC_NAME),'r') as f:
        spec = f.read()
        verison = re.search("Version:        ([\d.]+)\n",spec).group(1)
        release = re.search("define anolis_release (\d)\n",spec).group(1)
        print("[+] version = {}, release = {}".format(verison, release))

        print("[+] check change log")
        if not re.search(" - {}-{}".format(verison, release), spec):
            print("[-] leak of change log of {}-{} in {}".format(verison, release, SPEC_NAME))
            exit(1)
        
        date_items = re.findall(r"\* (\w+) (\w+) (\d+) (\d+) .*",spec)
        for date in date_items:
            _date = datetime.strptime("{} {} {}".format(date[3], date[1], date[2]),"%Y %b %d")
            if not _date.strftime("%a") == date[0]:
                print("[-] date error:'{}', should be '{}' in {}".format(date, _date.strftime("%a"), SPEC_NAME))
                exit(1)
    return verison, release

def packup():
    if os.path.exists("{}-{}".format(PACKAGE_NAME, version)):
        sysCommand("rm -rf {}-{}".format(PACKAGE_NAME, version))
    
    print("[+] create package dir: {}-{}".format(PACKAGE_NAME, version))
    sysCommand("mkdir {}-{}".format(PACKAGE_NAME, version))

    for file in PACKAGE_FILEs:
        print("[+] packup file: {}".format(file))
        
        sysCommand("cp -r {file} {pkg_name}-{version}".format(
            file = os.path.join(source_dir,file),
            pkg_name = PACKAGE_NAME,
            version = version))
    
    sysCommand("tar -cvzf {pkg_name}-{version}.tar.gz --exclude=**/__pycache__ {pkg_name}-{version}".format(
        pkg_name = PACKAGE_NAME, 
        version  = version,
    ))
    
    if os.path.exists("{}-{}".format(PACKAGE_NAME, version)):
        sysCommand("rm -rf {}-{}".format(PACKAGE_NAME, version))

def copySpec():
    print("[+] copy spec file from {}".format(os.path.join(source_dir, SPEC_NAME)))
    with open(os.path.join(source_dir, SPEC_NAME),'r') as f:
        spec = f.read()
    
    with open(os.path.join("./", SPEC_NAME),'w') as f:
        f.write(spec)
        
if __name__ == "__main__":
    version, release = checkspec()
    packup()
    copySpec()